package bank;

import java.util.ArrayList;
import java.util.List;

public class Bank {
	
	private  List<Account> accounts = new ArrayList<Account>();
	
	public synchronized void addAccount(Account acc) {
		accounts.add(acc);
	}
	
	public synchronized int getAllMoney() {
		int sum=0;
		for (Account a:accounts) {
			synchronized (a) {
			sum+=a.getMoney();
			}
		}
		return sum;
	}
	
	public void transferByIndexes(int from, int to, int amount) {
		transfer(accounts.get(from), accounts.get(to),amount);
	}
	
	public void transfer(Account from, Account to, int amount) {
		if (from.getId()==to.getId()) throw new IllegalArgumentException();
		Account first = (from.getId()<to.getId())?from:to;
		Account second = (from.getId()>to.getId())?from:to;
		synchronized (first) {
			synchronized(second) {
				int fromsMoney = from.getMoney();
				from.setMoney(fromsMoney-amount);
				int tosMoney = to.getMoney();
				to.setMoney(tosMoney+amount);
			}
		}
	}
}
